﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Rpc.Client;
using Wicture.QPZS.EPC.Models;

namespace Wicture.QPZS.EPC
{
    public class EpcRpcRouter : IRpcRouter
    {
        private Lazy<Dictionary<string, string>> servicesMap = new Lazy<Dictionary<string, string>>(LoadConfig);

        public static string ServiceV1 = "Wicture.EPC.Service.V1";
        public static string ServiceEtka = "Wicture.EPC.Service.Etka";
        public static string ServiceBenz = "Wicture.EPC.Service.Benz";

        private static Dictionary<string, string> LoadConfig()
        {
            var result = new Dictionary<string, string>();
            ConfigurationManager.Settings.Variables[ServiceV1].Split(",").ForEach(s => result.Add(s, ServiceV1));
            ConfigurationManager.Settings.Variables[ServiceEtka].Split(",").ForEach(s => result.Add(s, ServiceEtka));
            ConfigurationManager.Settings.Variables[ServiceBenz].Split(",").ForEach(s => result.Add(s, ServiceBenz));
            return result;
        }


        public (bool handled, string serviceName, string rpcApiName) Resolve(string implementationName, JToken param, IdentityInfo identity)
        {
            var brandCode = param.Value<string>("brandCode");

            string serviceName = servicesMap.Value.ContainsKey(brandCode) 
                ? servicesMap.Value[brandCode] 
                : throw new BrandNotSupportedException($"品牌代码`{brandCode}`暂时不支持。");

            return (true, serviceName, implementationName);
        }
    }
}
